package com.goodluck.goodluckim.network;

import com.goodluck.goodluckim.sdk.LogUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.CharsetUtil;

/**
 * Created by wyj on 2018/9/3.
 */
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private final WebSocketClientHandshaker handshaker;
    private ChannelPromise handshakeFuture;
    private WebSocketListener webSocketListener;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketListener webSocketListener) {
        this.handshaker = handshaker;
        this.webSocketListener = webSocketListener;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        webSocketListener.onServiceStatusConnectChanged(WebSocketListener.STATUS_CONNECT_SUCCESS);
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        webSocketListener.onServiceStatusConnectChanged(WebSocketListener.STATUS_CONNECT_CLOSED);
        LogUtils.printe("连接断开");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            LogUtils.printe("连接成功");
            handshakeFuture.setSuccess();
            webSocketListener.onServiceStatusConnectChanged(WebSocketListener.STATUS_CONNECT_SUCCESS);
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException(
                    "Unexpected FullHttpResponse (getStatus=" + response.status().code() +
                            ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
        }

        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            LogUtils.printe("接收到消息: " + textFrame.text());
            webSocketListener.onMessageReceived(textFrame.text());
        }
//        else if (frame instanceof PongWebSocketFrame) {
//            Log.e("Netty", "接收到心跳包回执");
//        } else if (frame instanceof CloseWebSocketFrame) {
//            Log.e("Netty", "接收到断开连接消息");
//            ch.close();
//        }
    }
}
